package unix

import (
	"context"
	"net"
	"net/rpc"
	"net/url"
	"ultone/internal/log"
	"ultone/internal/opt"
)

func Start(ctx context.Context) error {
	ready := make(chan bool)
	defer close(ready)

	uri, err := url.Parse(opt.RpcAddress)
	if err != nil {
		return err
	}

	address := uri.Host + uri.Path
	log.Debug(ctx, "[rpc-svc] listen at [%s] [%s]", uri.Scheme, address)

	ln, err := net.Listen(uri.Scheme, address)
	if err != nil {
		return err
	}

	go func() {
		ready <- true
		<-ctx.Done()
		_ = ln.Close()
	}()

	<-ready

	svc := rpc.NewServer()
	if err = svc.RegisterName("svc", &Handler{Ctx: ctx}); err != nil {
		return err
	}

	go func() {
		log.Info(ctx, "[rpc-svc] start at: [%s] [%s]", uri.Scheme, address)
		ready <- true
		svc.Accept(ln)
	}()

	<-ready

	return nil
}
